package com.thinkgem.jeesite.modules.qy.api;

import java.util.LinkedHashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.qy.dto.LoginDto;
import com.thinkgem.jeesite.modules.qy.entity.QyUser;
import com.thinkgem.jeesite.modules.qy.service.QyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 登录验证模块
 * 
 * @author chenweicheng
 * @version 2016-09-27
 */
@RestController
@RequestMapping(value = "front/authorize")
public class LoginApi extends BaseController {

	@Autowired
	private QyUserService  qyUserService;

	/**
	 * 登录
	 */	
	@RequestMapping(value = "login")
	public LinkedHashMap<String,Object> login(@Valid LoginDto login , BindingResult br,
											  HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		LinkedHashMap<String,Object> map = new LinkedHashMap<String,Object>();
		map.put("code", false);
		List<FieldError> errors = br.getFieldErrors();
		if(errors != null && !errors.isEmpty()){
			map.put("errMessage", errors.get(0).getDefaultMessage()); 
		}else{
		    QyUser qyUser =  qyUserService.validateUser(login);
			if(qyUser == null ){
				map.put("errMessage","用户名或密码有错");
			}else{
				map.put("code",true);
				//通过成功以后返回token,其中token就是sessionId
				HttpSession session = request.getSession(true);
				session.setAttribute(session.getId(),qyUser);
				map.put("token", session.getId());
			}
		}
		return map;
	}
	
}
